﻿using Company.Project.Application.Service.CacheService;
using Company.Project.Application.Service.Interface;
using Company.Project.Infrastructure.Utility.BaseEnums;
using Company.Project.Web.Admin.Areas.Admin.Lib;
using Company.Project.Web.Admin.Lib;
using Company.Project.Web.Areas.Admin.Attrbute;
using Company.Utility;
using Company.Utility.ImageUpload;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Company.Project.Domain.MainModule.Interface;

namespace Company.Project.Web.Areas.Admin.Controllers
{
    //
    public class HomeController : BaseController
    {

        private readonly IProject_Manager_BaseInfoServices _baseInfoServices;
        private readonly IProject_SYS_ModuleServices _moduleServices;
        private readonly IProject_SYS_ModuleActionServices _moduleActionServices;
        private readonly IProject_SYS_RoleServices _roleServices;
        private readonly IProject_SYS_RoleActionServices _roleActionServices;
        private readonly IProject_SYS_BaseCacheService _testCacheService;
        private readonly ILocalCommon _localCommon;
        public HomeController(
            IProject_Manager_BaseInfoServices baseInfoServices,
            IProject_SYS_ModuleServices moduleServices,
            IProject_SYS_ModuleActionServices moduleActionServices,
            IProject_SYS_RoleServices roleServices,
            IProject_SYS_RoleActionServices roleActionServices,
            IProject_SYS_BaseCacheService testCacheService, ILocalCommon localCommon
            ):base(localCommon)
        {
            _baseInfoServices = baseInfoServices;
            _moduleServices = moduleServices;
            _moduleActionServices = moduleActionServices;
            _roleServices = roleServices;
            _roleActionServices = roleActionServices;
            _testCacheService = testCacheService;
            _localCommon = localCommon;
        }

        // GET: Admin/Home

        [AllowAnonymous]
        public IActionResult GetEnum_ApiResultCode(Enum_ApiResultCode? code = null, bool isEmpty = false)
        {
            return Json(EnumHelper.EnumTypeGetListItem<Enum_ApiResultCode>(code?.GetValueToInt().ToString(), isEmpty));
        }

        [AllowAnonymous]
        public async Task<IActionResult> Login()
        {
            try
            {
                var user = CurrentUser;
                if (user.ID != Guid.Empty)
                {
                    await _baseInfoServices.CheckLogin(CurrentUser.LoginName, CurrentUser.PassWord, false, true);
                    return RedirectToAction("Index");
                }
            }
            catch (Exception)
            {
               await Common.LoginOut();
            }
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        
        [FormHandle]
        public async Task<IActionResult> CheckLogin(string remeberMe)
        {
            var result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                string sLoginName = Request.Form["sUserName"];
                Regex clearSpecialSymbol = new Regex("[?*=]");
                string sPassWord = clearSpecialSymbol.Replace(Request.Form["sPassword"], string.Empty);
                var rememberMe = remeberMe != null;
                var ValidateCode = Request.Form["ValidateCode"];
                await _baseInfoServices.CheckLogin(sLoginName, sPassWord, rememberMe, false, ValidateCode);
                x.Message = "登录成功!";
                x.Success = true;
            });
            return Json(result);
        }

        [AllowAnonymous]
        public async Task<IActionResult> LoginOut(string msg, bool goOut = true)
        {
            TempData["ErrMsg"] = msg;
            if (goOut)
            {
                await Common.LoginOut();
                return RedirectToAction("Login");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        
        [HttpPost]
        
        [FormHandle]
        public async Task<IActionResult> ChangeUserInfo(string nickName, string newPassword, string confirmPassword,
            int userChangeType, string oldpassword)
        {
            var result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                await
                    _baseInfoServices.ChangeUserInfo(CurrentUser.ID, nickName, newPassword, confirmPassword,
                        userChangeType, oldpassword);
                x.Message = userChangeType == 1 ? "密码修改成功" : "基本信息修改成功!";
                x.Success = true;
            });
            return Json(result);
        }

        [AllowAnonymous]
        public IActionResult VerCode()
        {
            //由于跨平台的原因,需内置字体文件用于生成验证码
            var codeImg = Verification.IdentifyingCode($"{Directory.GetCurrentDirectory()}/wwwroot/font/calibri.ttf",out var validateKey);
            Response.Cookies.Append("ValidateKey", validateKey);
            return File(codeImg, "image/png");
        }

        
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult MyDesktop()
        {
            return View();
        }

        [HttpPost]
        public IActionResult UploadTest(IFormFile file)
        {
            var FileItem = ProxyImageServices.UploadImage(file, "Admin", ProxyImageServices.CuteMode.W, 750, 0);
            return Content(ReadConfig.ReadAppSetting("ImageUploadUrl")+FileItem.filename);
        }

        public async Task<IActionResult> ChangeLoginInfo(int type)
        {
            if (type == 0)
            {
                return View("~/Areas/Admin/Views/Home/_ManagerInfo.cshtml",
                    (await _baseInfoServices.GetByKeyAsync(CurrentUser.ID)));
            }
            return View("~/Areas/Admin/Views/Home/_ManagerPwd.cshtml");
        }

        public async Task<IActionResult> GetLoginByAjax()
        {
            var result = new TipResult();
            await result.RunWithAsyncTry(async x =>
            {
                x.Success = true;
                var data = await _localCommon.CurrentFullUserAsync();
                var Menu = JsonConvert.DeserializeObject<dynamic>(data.Menu);
                x.Data = new { data.NickName, Menu };
            });
            return Json(result);
        }

        public IActionResult Test()
        {
            return View();
        }
    }
}